package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    //新增购物车
    @Override
    public Cart add(Cart cart) {
        //1.判断是否已经存在
        //select * from shopping_cart where user_id=#{用户登录的id} and dish_id=#{选择的菜品id}
        //select * from shopping_cart where user_id=#{用户登录的id} and setmeal_id=#{选择的套餐id}
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId())
                .eq(cart.getDishId()!=null,Cart::getDishId,cart.getDishId())
                .eq(cart.getSetmealId()!=null,Cart::getSetmealId,cart.getSetmealId());
        Cart cartFromDb = cartMapper.selectOne(wrapper);
        //2.已经存在就number+1
        if (cartFromDb != null) {
            cartFromDb.setNumber(cartFromDb.getNumber() + 1);
            cartMapper.updateById(cartFromDb);
            return cartFromDb;
        } else {
            //3.不存在，添加cart需要的数据保存
            cart.setNumber(1);
            cart.setCreateTime(new Date());
            cart.setUserId(UserHolder.get().getId());
            cartMapper.insert(cart);
            return cart;
        }

    }
    //查询指定用户的购物车列表
    @Override
    public List<Cart> findList() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        List<Cart> cartList = cartMapper.selectList(wrapper);
        return cartList;
    }
    //清空购物车
    @Override
    public void delete() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        cartMapper.delete(wrapper);
    }
    //修改购物车
    @Override
    public Cart update(Cart cart) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId())
                .eq(cart.getDishId()!=null,Cart::getDishId,cart.getDishId())
                .eq(cart.getSetmealId()!=null,Cart::getSetmealId,cart.getSetmealId());
        Cart cartFromDb = cartMapper.selectOne(wrapper);
        cartFromDb.setNumber(cartFromDb.getNumber()-1);
        if (cartFromDb.getNumber() == 0) {
            cartMapper.deleteById(cartFromDb.getId());

        }else {
            cartMapper.updateById(cartFromDb);

        }
        return cartFromDb;
    }
}
